package com.frkj.order.model;

import com.frkj.order.cache.BusinessCache;
import com.frkj.order.util.OrderConstant;
import com.frkj.order.vo.FullQueueInfo;
import com.frkj.order.vo.QueueCount;
import com.frkj.order.vo.WorkingOrder;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import java.util.*;

/**
 * Created by Administrator on 2016/6/27.
 *
 +---------------+--------------+------+-----+---------+-------+
 | Field         | Type         | Null | Key | Default | Extra |
 +---------------+--------------+------+-----+---------+-------+
 | number        | varchar(30)  | NO   | PRI | NULL    |       |
 | user_type     | int(11)      | NO   |     | NULL    |       |
 | open_id       | varchar(100) | YES  |     | NULL    |       |
 | business_id   | int(11)      | NO   |     | NULL    |       |
 | business_name | varchar(100) | NO   |     | NULL    |       |
 | business_tag  | varchar(30)  | NO   |     | NULL    |       |
 | operator_id   | int(11)      | YES  |     | NULL    |       |
 | operator_name | varchar(100) | YES  |     | NULL    |       |
 | status        | int(11)      | NO   |     | NULL    |       |
 | create_time   | datetime     | NO   |     | NULL    |       |
 | start_time    | datetime     | YES  |     | NULL    |       |
 | end_time      | datetime     | YES  |     | NULL    |       |
 | cost_time     | int(11)      | YES  |     | NULL    |       |
 | window        | int(11)      | YES  |     | NULL    |       |
 +---------------+--------------+------+-----+---------+-------+
 */
public class UserOrder extends Model<UserOrder> {

    public static final UserOrder me = new UserOrder();

    /**
     * 获取当前各业务类型排队信息
     * @return
     */
    public List<QueueCount> getWaitingQueueInfoList(int operatorId) {
        String sql = null;
        List<Record> recordList = null;
        if(operatorId != -1) {
            // 指定柜员，获取其业务范围内排队信息
            sql = "select business_name, count(number) as cnt from userorder where status=? and business_id in (select business_id from operator_business where operator_id=?) group by business_name";
            recordList = Db.find(sql, OrderConstant.ORDER_STATUS_WAITING, operatorId);
        } else {
            // 不指定柜员，获取全部业务排队信息
            sql = "select business_name, count(number) as cnt from userorder where status=? group by business_name";
            recordList = Db.find(sql, OrderConstant.ORDER_STATUS_WAITING);
        }

        List<QueueCount> queueCountList = new ArrayList<QueueCount>();
        for(Record record : recordList) {
            queueCountList.add(new QueueCount(record.getStr("business_name"), record.getLong("cnt").intValue()));
        }
        return queueCountList;
    }

    /**
     * 获取当前正在处理业务信息
     * @return
     */
    public List<WorkingOrder> getWorkingOrderList() {
        List<Record> recordList = Db.find("select number, window from userorder where status=?", OrderConstant.ORDER_STATUS_WORKING);
        List<WorkingOrder> workingOrderList = new ArrayList<WorkingOrder>();
        for(Record record : recordList) {
            workingOrderList.add(new WorkingOrder(record.getStr("number"), record.getStr("window")));
        }
        return workingOrderList;
    }

    /**
     * (用户)获取当前业务类型排号号码
     * @param businessId
     * @return
     */
    public int nextOrderNumber(int businessId) {
        Record record = Db.findFirst("select count(number)+1 as nextnumber from userorder where business_id=?", businessId);
        return record.getLong("nextnumber").intValue();
    }

    public QueueCount getBeforWaitingCount(int businessId) {
        Record record = Db.findFirst("select business_name, count(number) as cnt from userorder where business_id=? and status=?", businessId, OrderConstant.ORDER_STATUS_WAITING);
        return new QueueCount(record.getStr("business_name"), record.getLong("cnt").intValue() - 1);
    }

    /**
     * (管理员)叫号
     * @param operator
     * @param businessId
     * @param window
     * @return
     */
    public UserOrder callOrder(Operator operator, int businessId, int window) {
        UserOrder userOrder = null;
        String sql = null;
        int operatorId = operator.getInt("id");
        if(businessId != -1) {
            // 指定业务类型
            sql = "select * from userorder where status=? and business_id=? order by create_time asc";
            userOrder = UserOrder.me.findFirst(sql, OrderConstant.ORDER_STATUS_WAITING, businessId);
        } else {
            // 不指定业务类型
            sql = "select * from userorder where status=? and business_id in (select business_id from operator_business where operator_id=?) order by create_time asc";
            userOrder = UserOrder.me.findFirst(sql, OrderConstant.ORDER_STATUS_WAITING, operatorId);
        }

        userOrder.set("start_time", new Date());
        userOrder.set("status", OrderConstant.ORDER_STATUS_WORKING);
        userOrder.set("operator_id", operatorId);
        userOrder.set("operator_name", operator.getStr("name"));
        userOrder.set("window", window);
        userOrder.update();

        return userOrder;
    }

    /**
     * 获取全部业务所有状态统计信息
     * @return
     */
    public List<FullQueueInfo> getFullQueueInfo() {
        List<Business> businessList = BusinessCache.getBusinessList();
        Map<String, FullQueueInfo> fullQueueInfoMap = new LinkedHashMap<String, FullQueueInfo>();
        for(Business business : businessList) {
            fullQueueInfoMap.put(business.getStr("name"), new FullQueueInfo(business.getStr("name")));
        }

        List<Record> recordList = Db.find("select business_name, status, count(number) as cnt from userorder group by business_name, status");
        for(Record record : recordList) {
            String businessName = record.getStr("business_name");
            int status = record.getInt("status");
            long count = record.getLong("cnt");
            fullQueueInfoMap.get(businessName).setCount(status, count);
        }

        FullQueueInfo[] fullQueueInfos = new FullQueueInfo[fullQueueInfoMap.size()];
        fullQueueInfoMap.values().toArray(fullQueueInfos);
        return Arrays.asList(fullQueueInfos);
    }

    /**
     * 获取最新N个排队号码
     * @param count
     * @return
     */
    public List<UserOrder> getWaitingUserList(int count) {
        List<UserOrder> userOrderList = UserOrder.me.find("select * from userorder where status=? order by create_time asc limit ?", OrderConstant.ORDER_STATUS_WAITING, count);
        return userOrderList;
    }

    public void ignore(String number) {
        UserOrder userOrder = UserOrder.me.findById(number);
        userOrder.set("status", OrderConstant.ORDER_STATUS_IGNORE);
        userOrder.update();
    }

    public void end(String number) {
        UserOrder userOrder = UserOrder.me.findById(number);
        // 计算业务耗时
        Date startTime = userOrder.getDate("start_time");
        Date endTime = new Date();
        long cost = (endTime.getTime() - startTime.getTime())/60000;

        userOrder.set("end_time", endTime);
        userOrder.set("status", OrderConstant.ORDER_STATUS_END);
        userOrder.set("cost_time", new Long(cost).intValue());

        userOrder.update();
    }
 }
